import React, { useRef, useState, useContext, useEffect } from "react";
import {
  Box,
  Flex,
  Text,
  Button,
  VStack,
  useToast,
  AlertDialog,
  AlertDialogBody,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogOverlay,
  AlertDialogContent,
} from "@chakra-ui/react";
import { MainContext } from "@/src/providers/MainProvider";
import Image from "next/image";
import { useTranslation } from "@/src/i18n";
import { getImgPath } from "@/src/utils";

const imgPath = getImgPath();

interface SettingItem {
  name: string;
  tips: string;
  btn: string;
  status: "disable" | "normal" | "active";
  key: string;
}

const OtherSetting = () => {
  const {
    connectedMouse,
    restoreFactorySettings,
    deviceName,
    connectMode,
    deviceVersion,
    dongleVersion,
  } = useContext(MainContext);
  const { t } = useTranslation("");
  const mouseFirmwareVersion = t("mouseFirmwareVersion");
  const noNeedUpdate = t("noNeedUpdate");
  const receiverFirmwareVersion = t("receiverFirmwareVersion");

  const [mouseName, setMouseName] = useState<string>("g3");
  const [mouseNewVersion, setMouseNewVersion] = useState<string>("1.5.0");
  const [mouseUpdateTips, setMouseUpdateTips] = useState<string>(
    t("noNeedUpdate")
  );

  // 比较版本号
  const compareVersions = (current: string, newer: string) => {
    const currentParts = current.split(".").map(Number);
    const newerParts = newer.split(".").map(Number);

    for (let i = 0; i < Math.max(currentParts.length, newerParts.length); i++) {
      const currentPart = currentParts[i] || 0;
      const newerPart = newerParts[i] || 0;

      if (newerPart > currentPart) return true;
      if (newerPart < currentPart) return false;
    }
    return false;
  };

  useEffect(() => {
    if (deviceName.includes("G7")) {
      setMouseName("g7");
    } else if (deviceName.includes("A7e")) {
      setMouseName("A7e");
    } else if (deviceName.includes("G3 V2")) {
      setMouseName("g3_v2");
    } else {
      setMouseName("g3");
    }
    // console.log("deviceName", deviceName, mouseName);

    if (deviceName.includes("G7 Pro")) {
      setMouseNewVersion("2.2.3");
    } else if (deviceName.includes("G7")) {
      setMouseNewVersion("2.2.3");
    } else if (deviceName.includes("G3 V2")) {
      setMouseNewVersion("2.2.0");
    } else if (deviceName.includes("A7e Pro")) {
      setMouseNewVersion("2.0.0");
    } else if (deviceName.includes("A7e")) {
      setMouseNewVersion("2.0.0");
    } else {
      setMouseNewVersion("1.5.0");
    }

    const needsUpdate = compareVersions(deviceVersion, mouseNewVersion);
    // console.log("needsUpdate", needsUpdate);

    if (!needsUpdate) {
      setMouseUpdateTips(t("noNeedUpdate"));
    } else {
      setMouseUpdateTips(
        `${t("latestVersion")}：V${mouseNewVersion}，${t("pleaseUpdate")}`
      );
    }
  }, [deviceName, deviceVersion]);

  const [settings, setSettings] = useState<SettingItem[]>([
    {
      name:
        connectMode === "有线连接"
          ? mouseFirmwareVersion + deviceVersion
          : mouseFirmwareVersion,
      tips: connectMode === "有线连接" ? mouseUpdateTips : t("usbNotConnected"),
      btn:
        connectMode === "有线连接"
          ? deviceVersion === mouseNewVersion
            ? t("latest")
            : t("upgradeNow")
          : t("toBeConnected"),
      status: deviceVersion === mouseNewVersion ? "disable" : "normal",
      key: "mouseVersion",
    },
    {
      name:
        connectMode === "有线连接"
          ? receiverFirmwareVersion
          : receiverFirmwareVersion + dongleVersion,
      tips: connectMode === "有线连接" ? t("2.4gNotConnected") : noNeedUpdate,
      btn: connectMode === "有线连接" ? t("toBeConnected") : t("latest"),
      status: "disable",
      key: "receiverVersion",
    },
    {
      name: t("restoreFactorySetting"),
      tips: t("restoreFactoryTip"),
      btn: t("factoryRecovery"),
      status: "normal",
      key: "restoreFactorySetting",
    },
  ]);

  const [isOpen, setIsOpen] = useState(false);
  const toast = useToast();
  const cancelRef = useRef<HTMLButtonElement | null>(null);

  useEffect(() => {
    const needsUpdate = compareVersions(deviceVersion, mouseNewVersion);
    // console.log("needsUpdate", needsUpdate);

    setSettings([
      // {
      //   name:
      //     connectMode === "有线连接"
      //       ? mouseFirmwareVersion + deviceVersion
      //       : mouseFirmwareVersion,
      //   tips:
      //     connectMode === "有线连接" ? mouseUpdateTips : t("usbNotConnected"),
      //   btn:
      //     connectMode === "有线连接"
      //       ? deviceVersion === mouseNewVersion || !needsUpdate
      //         ? t("latest")
      //         : t("upgradeNow")
      //       : t("toBeConnected"),
      //   status:
      //     deviceVersion === mouseNewVersion || !needsUpdate
      //       ? "disable"
      //       : "normal",
      //   key: "mouseVersion",
      // },
      // {
      //   name:
      //     connectMode === "有线连接"
      //       ? receiverFirmwareVersion
      //       : receiverFirmwareVersion + dongleVersion,
      //   tips: connectMode === "有线连接" ? t("2.4gNotConnected") : noNeedUpdate,
      //   btn: connectMode === "有线连接" ? t("toBeConnected") : t("latest"),
      //   status: "disable",
      //   key: "receiverVersion",
      // },
      {
        name: t("restoreFactorySetting"),
        tips: t("restoreFactoryTip"),
        btn: t("factoryRecovery"),
        status: "normal",
        key: "restoreFactorySetting",
      },
    ]);
  }, [
    connectMode,
    deviceVersion,
    dongleVersion,
    mouseUpdateTips,
    mouseNewVersion,
  ]);

  const handleClick = (item: SettingItem) => {
    if (item.key === "mouseVersion") {
      const needsUpdate = compareVersions(deviceVersion, mouseNewVersion);

      if (!needsUpdate) {
        toast({
          title: t("firmwareVersion"),
          description: t("upDateFirmware"),
          status: "info",
          duration: 3000,
          isClosable: true,
          position: "top",
        });
        return;
      }

      if (deviceName.includes("G7 Pro")) {
        window.open("./firmware/G7Pro-Firmwaretool-2.2.3.zip");
      } else if (deviceName.includes("G7")) {
        window.open("./firmware/G7-Firmwaretool-2.2.3.zip");
      } else if (deviceName.includes("G3 V2")) {
        window.open("./firmware/G3-Firmwaretool-2.2.0.zip");
      }
    }
    if (item.key === "receiverVersion") {
      toast({
        title: t("firmwareVersion"),
        description: t("upDateFirmware"),
        status: "info",
        duration: 3000,
        isClosable: true,
        position: "top",
      });
      return;
    }

    if (item.key === "restoreFactorySetting") {
      setIsOpen(true);
    }
  };

  const handleConfirmRestore = async () => {
    await restoreFactorySettings(connectedMouse);
    toast({
      title: t("restoreFactorySetting"),
      description: t("mouseReset"),
      status: "success",
      duration: 3000,
      isClosable: true,
      position: "top",
    });
    setIsOpen(false);
  };

  const getMouseImg = () => {
    return `${imgPath}/products/mouse-v1000.png`;
  };

  return (
    <Flex justify="center" align="center" height="calc(100vh - 160px)" px={8}>
      <Image
        src={getMouseImg()}
        alt="Mouse"
        width={290}
        height={430}
        priority
        unoptimized
      />
      <Box marginLeft="48px" borderRadius="12px" className="transition-btn">
        <VStack spacing={6}>
          {" "}
          {settings.map((item, index) => (
            <Flex
              key={item.key}
              align="center"
              justify="space-between"
              w="full"
              h="100px" // height: 94px
              px={8} // padding-x: 32px
              py={4} // padding-y: 24px
              borderRadius="12px"
              bg="#211a31"
            >
              <Box>
                <Text fontSize="16px" fontWeight="700" color="white">
                  {item.name}
                </Text>
                <Text
                  fontSize="14px"
                  color={
                    item.tips.includes("检测到最新版本") ? "#0066FF" : "white"
                  }
                  opacity={item.status === "normal" ? 1 : 0.5}
                >
                  {item.tips}
                </Text>
              </Box>
              <Button
                bg="#0066ff"
                color={item.status === "normal" ? "white" : "white"}
                fontFamily="Microsoft YaHei"
                fontSize="13px"
                fontWeight={400}
                lineHeight="18px"
                whiteSpace="wrap"
                _hover={{
                  backgroundColor: "#428dff",
                }}
                onClick={() => handleClick(item)}
                isDisabled={item.status === "disable"}
              >
                {item.btn}
              </Button>
            </Flex>
          ))}
        </VStack>
      </Box>
      <AlertDialog
        isOpen={isOpen}
        onClose={() => setIsOpen(false)}
        leastDestructiveRef={cancelRef}
        isCentered
      >
        <AlertDialogOverlay>
          <AlertDialogContent mx="auto" my="auto" maxW="400px">
            <AlertDialogHeader
              fontSize="lg"
              fontWeight="bold"
              textAlign="center"
              color="white"
            >
              {t("restoreFactorySetting")}
            </AlertDialogHeader>

            <AlertDialogBody textAlign="center" color="white">
              {t("resetConfirm")}
            </AlertDialogBody>

            <AlertDialogFooter justifyContent="center">
              <Button
                variant="outline"
                onClick={() => setIsOpen(false)}
                mr={3}
                color="white"
              >
                {t("cancel")}
              </Button>
              <Button
                colorScheme="red"
                ref={cancelRef}
                onClick={handleConfirmRestore}
              >
                {t("restore")}
              </Button>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialogOverlay>
      </AlertDialog>
    </Flex>
  );
};

export default OtherSetting;
